package com.FTW.SAA.controller;

import com.FTW.SAA.entity.records.StudentRecord;
import com.FTW.SAA.tools.DateTimeTool;
import com.alibaba.cloud.ai.memory.redis.RedisChatMemoryRepository;
import jakarta.annotation.Resource;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.chat.prompt.ChatOptions;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.chat.prompt.PromptTemplate;
import org.springframework.ai.chat.prompt.SystemPromptTemplate;
import org.springframework.ai.model.tool.ToolCallingChatOptions;
import org.springframework.ai.support.ToolCallbacks;
import org.springframework.ai.tool.ToolCallback;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import java.util.List;
import java.util.Map;
import java.util.function.Consumer;

import static org.springframework.ai.chat.memory.ChatMemory.CONVERSATION_ID;

@RestController
@RequestMapping("/chat")
public class ChatController {

    @Resource(name = "ollamaChatModel")
    private ChatModel ollamaChatModel;

    @Resource
    @Qualifier("deepseek")
    private ChatModel deepSeekModel;

    @Resource
    @Qualifier("qwen3")
    private ChatModel qwen3Model;

    @Resource
    @Qualifier("deepSeekClient")
    private ChatClient deepSeekClient;

    @Resource
    @Qualifier("qwen3Client")
    private ChatClient qwen3Client;

    @Resource
    @Qualifier("ollamaClient")
    private ChatClient ollamaClient;

    @Resource
    private DateTimeTool dateTimeTool;

    @GetMapping("/doChat/Ollama")
    public String doChatWithOllamaModel(
            @RequestParam(value = "msg", defaultValue = "Java的强大之处在于？") String userQuestion,
            @RequestParam(value = "topic", defaultValue = "Java") String systemTopic) {
        SystemPromptTemplate systemPromptTemplate =  new SystemPromptTemplate("你是一名资深{systemTopic}程序员");
        Message systemMessage = systemPromptTemplate.createMessage(
                Map.of("systemTopic",systemTopic));

        PromptTemplate userPromptTemplate = new PromptTemplate("请解释该问题：{userQuestion}");
        Message userMessage = userPromptTemplate.createMessage(
                Map.of("userQuestion",userQuestion));

        Prompt prompt = new Prompt(List.of(systemMessage,userMessage));
        return ollamaChatModel.call(prompt).getResult().getOutput().getText();
    }

    @GetMapping("/doGet/Ollama")
    public StudentRecord doGetRecordWithOllamaModel(
            @RequestParam(value = "name") String Name,
            @RequestParam(value = "email") String Email) {
        return ollamaClient.prompt().user(new Consumer<ChatClient.PromptUserSpec>() {
            @Override
            public void accept(ChatClient.PromptUserSpec promptUserSpec) {
                promptUserSpec.text("学号1001，姓名{name}，主修课程软件技术，邮箱{email}")
                        .param("name", Name)
                        .param("email", Email);
            }
        }).call().entity(StudentRecord.class);
    }

    @GetMapping("/doGetTime")
    public String doGetTimeWithDeepSeekModel(@RequestParam(value = "msg") String userMessage) {
        if (dateTimeTool == null){
            return "方法就没传进去。";
        }

        //注册方法，让AI知道可以用这个方法获取当前时间
        ToolCallback[] toolCallbacks = ToolCallbacks.from(dateTimeTool);
        ChatOptions options = ToolCallingChatOptions.builder().toolCallbacks(toolCallbacks).build();
        //调用AI
        Prompt prompt = new Prompt(userMessage, options);
        return qwen3Model.call(prompt).getResult().getOutput().getText();
    }

    @GetMapping(value = "/doStreamChat/qwen3",produces = "text/plain;charset=UTF-8")
    public Flux<String> doStreamChatWithQwen3(@RequestParam(value = "msg", defaultValue = "你好呀！") String userMessage) {
        return qwen3Model.stream(userMessage);
    }

    @GetMapping(value = "/doStreamChat/deepseek",produces = "text/plain;charset=UTF-8")
    public Flux<String> doStreamChatWithDeepSeek(@RequestParam(value = "msg", defaultValue = "你好呀！") String userMessage) {
        return deepSeekModel.stream(userMessage);
    }

    @GetMapping("/doChat/client/deepseek")
    public String doChatWithDeepSeekClient(@RequestParam(value = "msg", defaultValue = "你好呀！") String userMessage) {
        return deepSeekClient.prompt(userMessage).call().content();
    }

    @GetMapping("/doChat/Memory/qwen")
    public String doChatAndMemoryWithQwen3(
            @RequestParam(value = "msg") String userMessage,
            @RequestParam(value = "uId") String userId){
        return qwen3Client.prompt(userMessage).advisors(new Consumer<ChatClient.AdvisorSpec>() {
            @Override
            public void accept(ChatClient.AdvisorSpec advisorSpec) {
                advisorSpec.param(CONVERSATION_ID,userId);
            }
        }).call().content();
    }
}
